package ai.people.core.feign.config;

import ai.people.netmon.framework.constant.CloudConstant;
import feign.RequestInterceptor;
import feign.RequestTemplate;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.Base64Utils;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Enumeration;

/**
 * 身份验证请求拦截器
 *
 * @author yuanqinglong
 * @date 2022/1/25 17:10
 */
@Slf4j
public class FeignAuthRequestInterceptor implements RequestInterceptor {


    @Override
    public void apply(RequestTemplate template) {
        String[] headerValues = {new String(Base64Utils.encode((CloudConstant.GATEWAY_TOKEN_VALUE).getBytes()))};
        template.header(CloudConstant.GATEWAY_TOKEN_HEADER, headerValues);
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        if (attributes == null) {
            return;
        }
        HttpServletRequest request = attributes.getRequest();
        Enumeration<String> headerNames = request.getHeaderNames();
        if (headerNames != null) {
            while (headerNames.hasMoreElements()) {
                String name = headerNames.nextElement();
                String values = request.getHeader(name);
                if (name.equals("content-length")) {
                    continue;
                }
                template.header(name, values);
            }
            log.info("feign interceptor header:{}", template);
        }
    }
}
